package org.marsdonne.audits.resolver;

import graphql.kickstart.tools.GraphQLQueryResolver;
import org.marsdonne.audits.Operation;
import org.marsdonne.audits.OperationFilters;
import org.marsdonne.audits.repos.OperationRepos;
import org.marsdonne.commons.jpa.FilterSpecSupport;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class OperationQueryResolver implements GraphQLQueryResolver, FilterSpecSupport<Operation> {
    @Resource
    private OperationRepos repos;

    public Iterable<Operation> getOperations(OperationFilters filters) {
        Specification<Operation> spec = null;

        if (filters != null) {
            if (filters.getEndpoint() != null)
                spec = by("endpoint", filters.getEndpoint());

            if (filters.getOperator() != null) {
                Specification<Operation> specPart = by("operator", filters.getOperator());
                spec = (spec == null) ? specPart : spec.and(specPart);
            }

            if (filters.getFunction() != null) {
                Specification<Operation> specPart = by("function", filters.getFunction());
                spec = (spec == null) ? specPart : spec.and(specPart);
            }

            if (filters.getCommand() != null) {
                Specification<Operation> specPart = by("command", filters.getCommand());
                spec = (spec == null) ? specPart : spec.and(specPart);
            }

            if (filters.getDateLogged() != null) {
                Specification<Operation> specPart = by("dateLogged", filters.getDateLogged());
                spec = (spec == null) ? specPart : spec.and(specPart);
            }
        }

        Sort sort = Sort.by("dateLogged").descending();

        if (spec == null)
            return repos.findAll(sort);
        else
            return repos.findAll(spec, sort);
    }
}
